package Maximum;


import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;
import Maximum.CondVar;

public class MaxAgent extends Agent{

	
	private int dataId;
	private String initialTime;
	private String finalTime;
	private float[] data =  new float[3];
	private String [] result =  new String[3];
	private CondVar cond=null;
	int max=-1;
	
    protected void setup() {
    	// Printout a welcome message
    	System.out.println("Hello! Max Agent "+getAID().getName()+" is ready.");
		// Register the sensors managing service 
		DFAgentDescription dfd = new DFAgentDescription();
		dfd.setName(getAID());
		ServiceDescription sd = new ServiceDescription();
		sd.setType("sensors-managing");
		sd.setName("JADE-sensors-measure");
		dfd.addServices(sd);
		try 
		{
			DFService.register(this, dfd);
		} catch (FIPAException fe) 
		{
			fe.printStackTrace();
		}
    	setEnabledO2ACommunication(true,1);
		// Notify blocked threads that the agent is ready and that
	      // object-to-agent communication is enabled
	      Object[] args = getArguments();
	      if(args.length == 2) {
	    	  cond=(CondVar)args[0];
	    	  Object[] o=(Object[])args[1];	    	  
	    	  dataId = Integer.parseInt(o[0].toString());
	    	  initialTime=o[1].toString();
	    	  finalTime=o[2].toString();
	      }
    	
        addBehaviour(new RequestPerformer());
	      }
	  
    
  
	  protected void takeDown() {
	    // Deregister 
	    try {
	      DFService.deregister(this);
	    } catch (FIPAException fe) {
	      fe.printStackTrace();
	    }
	    // Printout a dismissal message
	    System.out.println("Max. agent "+getAID().getName()+" terminating.");
	  }
	  
	  private class RequestPerformer extends CyclicBehaviour 
	  {
			//private MessageTemplate mt; // The template to receive reply.
			private int step = 0;
			private int nr=0;
			
			public void action() {
			   
			    if (step ==0)
			    {
			    	AID server= new AID();				
					server.setName("ServerAgent@"+/*TinaPC:1099/JADE"*/myAgent.getHap());
					String message=dataId+" "+initialTime+" "+finalTime;		
			      // Send the cfp to server agent
			      ACLMessage cfp = new ACLMessage(ACLMessage.REQUEST);
			      cfp.setSender(getAID());
	              cfp.addReplyTo(getAID());
	              cfp.addReceiver(server);
	              cfp.setContent(message);
			      //cfp.setConversationId("sensors-measure");
			      //cfp.setReplyWith("cfp"+System.currentTimeMillis()); // Unique value
			      myAgent.send(cfp);
			      // Prepare the template to get proposals
			      //mt = MessageTemplate.and(MessageTemplate.MatchConversationId("sensors-measure"),
			                              // MessageTemplate.MatchInReplyTo(cfp.getReplyWith()));
			      step = 1;
			    }
			    else
			    {
			      // Receive data from server agent
			      ACLMessage reply = myAgent.receive();
			      if (reply != null) {
			        // Reply received
			    	  {
						if(step==1)
							{
								String response=reply.getContent();
								int x=-1;
								try{
									x=Integer.parseInt(response.trim());
								}catch(Exception e){
									
								}
								if(x!=-1)
								{
									max=x;
									data=new float[max];
									result=new String[max];
									System.out.println("Receiving "+max+" data");
								}
							}
							else
							{
								String response[]=reply.getContent().trim().split(" ");
								if(response.length==2)
								{
									data[nr]=Float.parseFloat(response[0]);
									result[nr]=response[1];
									System.out.println("Received: "+data[nr]);
									nr++;						
								}					
							}
							
							try{			
								String mess="ok";						
								ACLMessage reply2 = new ACLMessage(ACLMessage.CONFIRM);
								reply2.setSender(getAID());
								reply2.addReplyTo(getAID());
								reply2.addReceiver(reply.getSender());
								reply2.setContent(mess);
								send(reply2);
								}catch(Exception e){
									e.printStackTrace();
								}
								
							step = 2;
							if(nr>=max)
							{
								System.out.println("Finished receiving data");
								
								cond.signal(data);
								
								myAgent.doSuspend();
							}
							}
							
						
						}
						
					}
				};
	  }
	 

 
}

